package com.czxy.user.controller;


import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czxy.domain.TbEnPhoto;
import com.czxy.domain.TbEnterprise;
import com.czxy.domain.TbPhoto;
import com.czxy.domain.TbUser;
import com.czxy.findjob.utils.JwtUtils;
import com.czxy.findjob.utils.RsaUtils;
import com.czxy.findjob.vo.BaseResult;
import com.czxy.user.config.JwtProperties;
import com.czxy.user.config.OssProperties;
import com.czxy.user.feign.EnterpriseFeign;
import com.czxy.user.feign.PhotoFeign;
import com.czxy.user.service.SmsService;
import com.czxy.user.service.UserService;
import com.czxy.user.utils.OssUtils;
import com.czxy.vo.ConditionUser;
import com.czxy.vo.MonthVo;
import com.czxy.vo.UserVo;
import javafx.print.PaperSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xuewen
 * @since 2022-02-06
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Autowired
    private OssUtils ossUtils;
    @Autowired
    private PhotoFeign photoFeign;
    @Autowired
    private EnterpriseFeign enterpriseFeign;
    @Autowired
    private SmsService smsService;

    @PostMapping("/login")
    public BaseResult login(@RequestBody TbUser tbUser){
        try {
            String token= "";
            TbUser user = userService.login(tbUser);
            System.out.println(user);

            if (user==null){
                return BaseResult.error("手机号码或密码错误");
            }
            if (user.getState()==2){
                return BaseResult.error("账号已被封禁");
            }
                token = JwtUtils.generateToken(user, jwtProperties.getExpire(), RsaUtils.getPrivateKey(jwtProperties.getPriKeyPath()));
                return BaseResult.ok("登录成功!",user).append("token",token);

        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.error("token生成失败");
        }
    }
    @PostMapping("/register")
    public BaseResult register(@RequestBody TbUser tbUser){
        try {
            userService.register(tbUser);
            return BaseResult.ok("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.error(e.getMessage());
        }

    }

    @PostMapping("/adminLogin")
    public BaseResult adminLogin(@RequestBody TbUser tbUser){
        try {
            String token= "";
            TbUser user = userService.login(tbUser);
            if (user==null || user.getLevel()==1){
                return BaseResult.error("手机号码或密码错误");
            }else {
                 token = JwtUtils.generateToken(user, jwtProperties.getExpire(), RsaUtils.getPrivateKey(jwtProperties.getPriKeyPath()));
                Map<String,String> map = new HashMap<>();
                map.put("token",token);
                return BaseResult.ok("登录成功",map);
            }
        } catch (Exception e) {

            return BaseResult.error("token生成失败");
        }
    }
    @GetMapping("/info")
    public BaseResult getInfo(String token) {
        System.out.println(token);
        Map<String,Object> map = new HashMap<>();
        UserVo user =null;
        try {
            user = JwtUtils.getObjectFromToken(token, RsaUtils.getPublicKey(jwtProperties.getPubKeyPath()), UserVo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.error("解析失败");
        }
        map.put("roles", Arrays.asList("admin"));
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("name", user.getUsername());
        return BaseResult.ok("登录成功",map);
    }

    @PostMapping("/upload/{id}")
    public BaseResult upload(@RequestParam("file") MultipartFile file,@PathVariable("id") Integer id){
        String url = ossUtils.upload(file);
        TbPhoto tbPhoto = new TbPhoto();
        tbPhoto.setPhotoUrl(url);
        BaseResult<TbPhoto> save = photoFeign.save(tbPhoto);
        TbPhoto photo = save.getData();
        TbUser tbUser = userService.getById(id);
        tbUser.setPhotoId(photo.getId());
        userService.updateById(tbUser);
        return BaseResult.ok("上传成功",photo);
    }
    @GetMapping("/findUserByEnterprise/{id}")
    public BaseResult findUserByEnterprise(@PathVariable("id") Integer id){
        TbEnterprise tbEnterprise = enterpriseFeign.findById(id).getData();
        TbUser tbUser = userService.getById(tbEnterprise.getUserId());
        TbPhoto tbPhoto = photoFeign.findById(tbUser.getPhotoId() + "").getData();
        tbUser.setPhoto(tbPhoto);
        return BaseResult.ok("查询成功",tbUser);
    }
    @GetMapping("/{id}")
    public BaseResult<TbUser> findById(@PathVariable("id") Integer id){
        TbUser tbUser = userService.getById(id);
        if (tbUser.getPhotoId()!=null){
            TbPhoto tbPhoto = photoFeign.findById(tbUser.getPhotoId() + "").getData();
            tbUser.setPhoto(tbPhoto);
        }
        return BaseResult.ok("查询成功",tbUser);
    }
    @PostMapping("/condition")
    public BaseResult condition(@RequestBody ConditionUser conditionUser){

        Page  page = userService.condition(conditionUser);
        return BaseResult.ok("查询成功",page);
    }
    @PutMapping("/upLevel/{id}")
    public BaseResult upLevel(@PathVariable("id") Integer id){
        TbUser tbUser = userService.getById(id);
        tbUser.setLevel(2);
        userService.updateById(tbUser);
        return BaseResult.ok("升级成功!");
    }
    @PutMapping("/downLevel/{id}")
    public BaseResult downLevel(@PathVariable("id") Integer id){
        TbUser tbUser = userService.getById(id);
        tbUser.setLevel(1);
        userService.updateById(tbUser);
        return BaseResult.ok("降级成功!");
    }
    @PutMapping("/ban/{id}")
    public BaseResult ban(@PathVariable("id") Integer id){
        TbUser tbUser = userService.getById(id);
        tbUser.setState(2);
        userService.updateById(tbUser);
        enterpriseFeign.banByUserId(tbUser.getId());
        return BaseResult.ok("封禁成功!");
    }
    @PutMapping("/unBan/{id}")
    public BaseResult unBan(@PathVariable("id") Integer id){
        TbUser tbUser = userService.getById(id);
        tbUser.setState(1);
        userService.updateById(tbUser);
        enterpriseFeign.unBanByUserId(tbUser.getId());
        return BaseResult.ok("解封成功!");
    }
    @GetMapping("/findByCandidateId/{id}")
    public BaseResult<TbUser> findByCandidateId(@PathVariable("id") Integer id){
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("candidates_id",id);
        TbUser tbUser = userService.getOne(queryWrapper);
        tbUser.setPhoto(photoFeign.findById(tbUser.getPhotoId()+"").getData());
        return BaseResult.ok("查询成功",tbUser);
    }
    @PostMapping("/sendCode")
    public BaseResult sendCode(@RequestBody TbUser user) {
        if (user.getPhone().length()!=11){
            return BaseResult.error("请输入正确的手机号");
        }
        try {
            boolean b = smsService.sendSmsCai(user);
            if (b){
                return BaseResult.ok("发送成功");
            }else{
                return BaseResult.error("发送失败");
            }
        } catch (ClientException e) {
            return BaseResult.error("发送失败");
        }
    }
    @PostMapping("/reSetPassword")
    public BaseResult reSetPassword(@RequestBody TbUser tbUser){
        try {
            boolean b = userService.reSetPassword(tbUser);
            if (b){
                return BaseResult.ok("修改成功");
            }else{
                return BaseResult.error("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.error(e.getMessage());
        }
    }
    @GetMapping("/findCount")
    public BaseResult findCount(){
        MonthVo monthVo = userService.findCountByDate();
        return BaseResult.ok("查询成功",monthVo);
    }
}

